<?php
/**
 * Created by PhpStorm.
 * User: papa
 * Date: 18/5/10
 * Time: 11:48
 */

namespace app\api\controller\v2;


use app\api\lib\exception\MissException;
use app\api\lib\exception\SuccessMessage;
use app\api\model\User;
use app\api\service\TokenService;
use app\api\service\UserToken;
use app\api\service\WxBizDataCrypt;
use think\Cache;

class UserController extends BaseController
{

    //此控制器全部方法都需要token认证，所以加入构造方法
    public function _initialize()
    {
        TokenService::checkLogin();
        $this->uid = UserToken::getCurrentUid();
    }

    /*
     * 授权后获取用户详细资料
     */
    public function getUserInfo()
    {
        $userInfo = input('post.data/a');
        $user = User::find($this->uid);
        $data['nickname'] = $userInfo['nickName'];
        $data['gender'] = $userInfo['gender'];
        $data['avatar_url'] = $userInfo['avatarUrl'];
        $data['city'] = $userInfo['city'];
        $data['province'] = $userInfo['province'];
        $data['country'] = $userInfo['country'];
//        dump($user);
        if((new User())->isUpdate(true)->save($data,['id'=>$this->uid])) {
            throw new SuccessMessage();
        }else{
            throw new MissException(['msg'=>'写入数据库失败',]);
        }
    }

    /*
     * 获取用户资料
     */
    public function getUser()
    {
        $uid = TokenService::getCurrentUid();
        $user = User::get($uid);
        throw new SuccessMessage(['data' => $user]);
    }

    //获取用户的所有信息资料
    public function getUserAllInfo()
    {
//        dump(Cache::get());
        $data = User::with('UserLevel')->find($this->uid);
        if($data) {
            throw new SuccessMessage(['data'=>$data]);
        }else{
            throw new MissException(['msg'=>'查询的数据不存在!']);
        }
    }
    
    /*
     * 获取用户手机号
     */
    public function getTel()
    {
        $session_key = TokenService::getCurrentTokenVar('session_key');
        $wx = new WxBizDataCrypt($session_key);
        $post = request()->post();
        $wx->decryptData($post['data']['encryptedData'],$post['data']['iv'],$data);
        $user = User::find($this->uid);
        $data = json_decode($data,true);
        $user->tel = $data['purePhoneNumber'];
        if($user->save()){
            throw new SuccessMessage(['msg'=>'用户手机号成功存入数据库']);
        }else{
            throw new MissException(['msg'=>'手机号存储失败',]);
        }
    }
}